package com.qingyun.web.controller.wxapi;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.*;
import com.qingyun.shop.domain.bo.apply.TiktokApplyProxyAddBo;
import com.qingyun.shop.domain.bo.branch.TiktokBranchRecordBo;
import com.qingyun.shop.domain.bo.shop.TiktokShopEditBo;
import com.qingyun.shop.domain.vo.TiktokActivityVo;
import com.qingyun.shop.domain.vo.TiktokBranchRecordVo;
import com.qingyun.shop.mapper.TiktokApplyProxyMapper;
import com.qingyun.shop.mapper.TiktokShopMapper;
import com.qingyun.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "小程序-商户信息管理")
@RestController
@RequestMapping("/miniapp/shop")
@AllArgsConstructor
public class ShopInfoController extends BaseController {

    private final TiktokShopMapper shopMapper;

    private final ITiktokShopService iTiktokShopService;

    private final ITiktokCouponService couponService;

    private final ITiktokApplyProxyService applyProxyService;

    private final TiktokApplyProxyMapper applyProxyMapper;

    private final ITiktokBranchRecordService branchRecordService;

    private final ITiktokProxyService proxyService;


    private final MapperFacade mapperFacade;

    @ApiOperation("商户信息")
    @GetMapping("/info")
    public AjaxResult info() {

        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();

        TiktokShop shop = shopMapper.selectById(shopId);

        return AjaxResult.success(shop);
    }

    @ApiOperation("商户信息修改")
    @PostMapping("/edit")
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokShopEditBo bo) {
        return toAjax(iTiktokShopService.updateByBo(bo) ? 1 : 0);
    }

    @ApiOperation("获取商家券张数量、用户余额、核销总数")
    @GetMapping("/getShopCouponData")
    public AjaxResult getShopCouponData(){
		Long id = SecurityUtils.getAppLoginUser().getShop().getId();
		List<TiktokCoupon> list = couponService.lambdaQuery().select(TiktokCoupon::getQuantity).eq(TiktokCoupon::getShopId, id).in(TiktokCoupon::getStatus,0,1).list();
		long sum = list.stream().mapToLong(k -> k.getQuantity()).sum();

		TiktokShop tiktokShop = shopMapper.selectOne(Wrappers.lambdaQuery(TiktokShop.class).select(TiktokShop::getVideoCount).eq(TiktokShop::getId,id));
		Long videoCount = tiktokShop.getVideoCount();
		Integer checkCount = couponService.selectCheckCount(id);
		Map<String, Object> map = new HashMap<>();
		map.put("couponCount",sum);
		map.put("videoCount",videoCount);
		map.put("checkCount", checkCount);

		return AjaxResult.success(map);
	}

    @ApiOperation("商户申请成为代理商")
    @PostMapping("/applyProxy")
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokApplyProxyAddBo bo) {
        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();
		int count = applyProxyService.count(Wrappers.lambdaQuery(TiktokApplyProxy.class).eq(TiktokApplyProxy::getShopId, shopId).in(TiktokApplyProxy::getStatus, 0));
		if(count>0){
			return AjaxResult.error("你的申请正在审核中，请耐心等待");
		}
        applyProxyService.checkShopIsProxy(shopId);
        TiktokApplyProxy applyProxy = mapperFacade.map(bo, TiktokApplyProxy.class);
        applyProxy.setApplyTime(new Date());
        applyProxy.setShopId(shopId);
        applyProxy.setUserId(SecurityUtils.getAppLoginUser().getSysUser().getUserId());
        return toAjax(applyProxyService.save(applyProxy) ? 1 : 0);
    }

    @ApiOperation("查询申请代理商的流程状态  流程状态 0审核中 1通过 2未通过 3还未申请")
    @GetMapping("/checkApplyProxy")
    public AjaxResult checkApplyProxy() {
        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();
        LambdaQueryWrapper<TiktokApplyProxy> lqw = Wrappers.lambdaQuery();
        lqw.eq(TiktokApplyProxy::getShopId, shopId);
        lqw.orderByDesc(TiktokApplyProxy::getId);
        lqw.last("limit 1");
        TiktokApplyProxy applyProxy = applyProxyMapper.selectOne(Wrappers.query(new TiktokApplyProxy().setShopId(shopId)));
        if (applyProxy == null) {
            return AjaxResult.success(3);
        }
        return AjaxResult.success(applyProxy.getStatus());
    }

    @ApiOperation("获取返利列表")
    @GetMapping("getBranchList")
    public TableDataInfo<TiktokBranchRecordVo> getBranchList(TiktokBranchRecordBo tiktokBranchRecordBo){
		TableDataInfo<TiktokBranchRecordVo> tiktokBranchRecordVoTableDataInfo = branchRecordService.queryPageList(tiktokBranchRecordBo);
		return tiktokBranchRecordVoTableDataInfo;
	}

	@ApiOperation("代理商获取余额")
	@GetMapping("getBalance")
	public AjaxResult getBalance(){
		if (!SecurityUtils.isProxy()) {
			return AjaxResult.error("你没有权限获取此数据");
		}
		Long id = SecurityUtils.getProxy().getId();
		TiktokProxy one = proxyService.lambdaQuery()
			.select(TiktokProxy::getTotalBalance,
				TiktokProxy::getUsableBalance,
				TiktokProxy::getFreezeBalance)
			.eq(TiktokProxy::getId, id).one();
		return AjaxResult.success(one);
    }



}
